<template>
  <div class="container">
    <div class="song-info">
      <div class="img">
        <img
          @click="transitionToPlayPage"
          :src="
            songInfo.picUrl ||
            'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3543933920,933288888&fm=26&gp=0.jpg'
          "
          alt=""
        />
        <div class="modal">{{ fold }}</div>
      </div>
      <div class="song">
        <p class="song-name">{{ songInfo.songName || "" }}</p>
        <p class="song-author">{{ songInfo.authorName || "" }}</p>
      </div>
    </div>
    <div class="controls">
      <div class="top">
        <span
          class="iconfont mode cm"
          :class="[currentIco]"
          @click="changeMode"
        ></span>
        <span class="mode cm"></span>
        <a-icon type="step-backward" class="cn prev" @click="prevSong" />
        <div class="run-bg">
          <a-icon :type="type" class="run cm" @click="playMusic('pause')" />
          <span></span>
        </div>
        <a-icon type="step-forward" class="next cm" @click="nextSong" />
      </div>
      <div class="play">
        <span class="start">{{ currentTime }}</span>
        <div class="prograss" @click.prevent="handleClick">
          <div class="move" :style="{ width: moveWidth + 'px' }"></div>
          <div
            @mousedown.prevent="handleDown"
            class="head"
            ref="head"
            :style="{ left: moveWidth - 5 + 'px' }"
          ></div>
        </div>
        <span class="end">{{ duration }}</span>
      </div>
    </div>
    <div class="others">
      <span class="quality cm"> 极高 </span>
      <span class="volume cm iconfont icon-yinliangdefuben"></span>
      <div class="volume-prograss cm">
        <div class="v-p"></div>
      </div>
      <a-icon type="menu-unfold" class="cm menu-unfold" />
    </div>
    <audio ref="audio"></audio>
  </div>
</template>

<script>
import axios from "@/utils/axios";
export default {
  name: "Player",
  props: {
    srcs: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      moveWidth: 0,
      run: false,
      duration: "00: 00",
      currentTime: "00: 00",
      songInfo: {},
      ids: [], // 存放所有歌曲id
      init: true,
      type: "caret-right",
      icos: ["icon-xunhuan1", "icon-xunhuan", "icon-suijibofang"],
      currentIco: "icon-xunhuan1",
      modeIndex: 0,
      preIds: [],
      fold: "展开", // 显示的是展开
      id: "", //歌曲id
      checkToNormal: false, // 随机播放切到正常循环标志
      singleCirculationId: "", // 单曲循环
      isSingle: false,
      isChange: true, // 是否移动滚动条
    };
  },
  methods: {
    // 拖动滚动条事件
    handleDown(e) {
      let left = 0;
      let leftVal = e.clientX - this.head.offsetLeft;
      document.onmousemove = (ev) => {
        // 更新时间
        this.resolveTotalTime(this.totalTime);
        this.isChange = false;
        left = ev.clientX - leftVal;
        if (left < 0) {
          left = 0;
          this.currentTime = '00: 00'
        } else if (left > 360) {
          left = 360;
        }
        // 改变滚动条
        this.moveWidth = left;
        // 更新时间， 根据当前的位置计算
        let {minutes, seconds} = this.resolveUpdateTime((left / 360) * this.totalTime);
        this.currentTime = `${minutes}: ${seconds}`;
        // let width = this.moveWidth;
        // let aLeft = width + ev.movementX;
        // if (aLeft < 0) {
        //   aLeft = 0;
        // } else if (aLeft > 360) {
        //   aLeft = 360;
        // }
        // this.moveWidth = aLeft;
      };
      document.onmouseup = document.onmouseleave = () => {
        this.isChange = true;
        // 改变播放时间
        this.audio.currentTime = (left / 360) * this.totalTime;
        document.onmousemove = null;
      };
      //防止选择内容--当拖动鼠标过快时候，弹起鼠标，bar也会移动，修复bug
      window.getSelection
        ? window.getSelection().removeAllRanges()
        : document.selection.empty();
    },
    // 点击移动滚动条
    handleClick(e) {
      if (e.target.classList.contains("head")) {
        return;
      }
      let x = e.offsetX;
      if (e.offsetX) {
        let currentTime = (x / 360) * this.totalTime;
        this.audio.currentTime = currentTime;
      }
    },
    // 改变展开或者收缩
    // 跳转到播放页面
    transitionToPlayPage() {
      const url = "/playPage/" + this.id;
      if (window.location.pathname === url && this.fold === "展开") {
        return;
      }
      if (this.fold === "展开") {
        this.fold = "收缩";
        this.$router.push(url);
      } else {
        this.fold = "展开";
        let path = sessionStorage.getItem("prevPath") || "/";
        this.$router.push(path);
      }
    },
    // 获取原始的数组
    getIds() {
      let ids = localStorage.getItem("ids");
      if (ids) {
        ids = JSON.parse(ids);
      }
      return ids || [];
    },
    // 改变模式
    changeMode() {
      this.modeIndex = ++this.modeIndex % this.icos.length;
      this.currentIco = this.icos[this.modeIndex];
      if (this.currentIco === "icon-suijibofang") {
        this.ids.sort((a, b) => Math.random() - 0.5);
        // 取消单曲循环
        this.isSingle = false;
      } else if (this.currentIco === "icon-xunhuan1") {
        this.ids = this.getIds();
        this.checkToNormal = true;
        // 取消单曲循环
        this.isSingle = false;
      } else {
        // 单曲循环
        this.singleCirculationId = this.id;
        this.isSingle = true;
      }
    },
    playMusic() {
      if (this.type === "pause") {
        this.audio.pause();
        // 改变state的running
        this.$store.commit("changeStatus", false);
        this.$bus.$emit("changeStutas");
        this.type = "caret-right";
      } else {
        this.audio.play();
        this.type = "pause";
        this.$store.commit("changeStatus", true);
        this.$bus.$emit("changeStutas");
      }
    },
    // 播放更新时间
    resolveUpdateTime(timeDisplay) {
      let minute = timeDisplay / 60;
      let minutes = parseInt(minute);
      if (minutes < 10) {
        minutes = "0" + minutes;
      }
      //秒
      let second = timeDisplay % 60;
      let seconds = Math.round(second);
      if (seconds < 10) {
        seconds = "0" + seconds;
      }
      return {
        minutes,
        seconds,
      };
    },
    resolveTotalTime(duration) {
      let t;
      let musicTime = duration - 1; // 获得音频时长
      let rightMinutes = Math.floor(musicTime / 60); // 计算音频分钟
      let rightSeconds = Math.ceil(musicTime % 60); // 计算音频秒
      if (rightMinutes < 10 && rightSeconds < 10) {
        // 四种情况判断音频总时间
        t = `0${rightMinutes}:0${rightSeconds}`;
      } else if (rightMinutes < 10) {
        if (rightSeconds < 60) {
          t = `0${rightMinutes}:${rightSeconds}`;
        } else if (rightSeconds === 60) {
          t = `0${rightMinutes + 1}:00`;
        }
      } else if (rightSeconds < 10) {
        t = `${rightMinutes}:0${rightSeconds}`;
      } else {
        t = `${rightMinutes}:${rightSeconds}`;
      }
      return t;
    },
    getI(i) {},
    // 下一首
    next(i) {
      if (this.isSingle) {
        return i;
      }
      if (this.currentIco === "icon-xunhuan1" && this.checkToNormal) {
        // 根据当前的id, 从而更新i
        let index = this.ids.findIndex((item) => this.id === item);
        this.checkToNormal = false;
        i = index + 1;
      } else {
        i++;
      }
      return i % this.ids.length;
    },
    //上一首
    prev(i) {
      if (this.isSingle) {
        return i;
      }
      if (this.currentIco === "icon-xunhuan1" && this.checkToNormal) {
        // 根据当前的id, 从而更新i
        let index = this.ids.findIndex((item) => this.id === item);
        this.checkToNormal = false;
        i = index - 1;
      } else {
        i--;
      }
      if (i < 0) {
        i = this.ids.length - 1;
      }
      return i;
    },
    // 初始化播放器
    initPlayer(src) {
      // 设置播放地址
      let audio = this.audio;
      audio.src = src;
      this.totalTime = 0;
      // 加载成功
      audio.oncanplay = () => {
        // 如果已经初始化过了，直接返回
        if (this.totalTime) {
          return;
        }
        this.totalTime = audio.duration;
        // 处理总时间
        this.duration = this.resolveTotalTime(this.totalTime);
        if (this.init) {
          this.init = false;
        } else {
          this.playMusic();
        }
      };
    },
    nextSong() {
      // 如果播放列表为空，直接返回
      if (!this.ids.length) {
        return;
      }
      this.i = this.next(this.i);
      this.setRequest(this.ids[this.i]);
    },
    prevSong() {
      // 如果播放播放列表为空
      if (!this.ids.length) {
        return;
      }
      this.i = this.prev(this.i);
      this.setRequest(this.ids[this.i]);
    },
    // 获取歌曲详情
    setRequest(id) {
      if (id) {
        // 让播放页面得到这首歌信息
        this.$bus.$emit("getSong", { id, audio: this.audio });
        this.id = id;
        axios.get("/song/url", { params: { id } }).then((res) => {
          this.moveWidth = 0;
          this.type = "caret-right";
          this.initPlayer(res.data[0].url);
          localStorage.setItem("id", id);
        });
        axios.get("/song/detail", { params: { ids: id } }).then((res) => {
          const info = {};
          info.picUrl = res.songs[0].al.picUrl;
          info.songName = res.songs[0].name;
          info.authorName = res.songs[0].ar[0].name;
          this.songInfo = info;
        });
      }
    },
    onTimeUpdate() {
      let currentTime = this.audio.currentTime;
      if (this.isChange) {
        this.moveWidth = (currentTime / this.totalTime) * 360;
      }
      let timeDisplay = Math.floor(currentTime); //获取实时时间
      //处理播放时间
      let { minutes, seconds } = this.resolveUpdateTime(timeDisplay);
      this.currentTime = `${minutes}: ${seconds}`;
    },
  },
  created() {
    this.$bus.$on("changeId", (id) => {
      // 保存当前播放的id
      // this.id = id;
      this.ids.push(id);
      localStorage.setItem("ids", JSON.stringify(this.ids));
      this.setRequest(this.ids[this.ids.length - 1]);
    });
    // 提供多个歌曲ids
    this.$bus.$on("provideIds", (ids) => {
      if (Array.isArray(ids) && ids.length) {
        this.ids = ids;
        localStorage.setItem("ids", JSON.stringify(this.ids));
        this.setRequest(ids[0]);
      }
    });
    this.$bus.$on("changeFoldContent", (txt) => {
      this.fold = txt;
    });
  },

  mounted() {
    this.i = 0;
    this.audio = this.$refs.audio;
    this.$store.commit("setAudio", this.audio);
    this.audio = this.$store.state.audio;
    // 播放中
    this.audio.addEventListener("timeupdate", this.onTimeUpdate);

    //播放结束
    this.audio.onended = () => {
      this.moveWidth = 360;
      this.nextSong();
    };

    if (this.srcs.length) {
      this.initPlayer(this.srcs[this.i]);
    }
    // 获取上次的列表，播放第一首歌
    let ids = localStorage.getItem("ids");
    if (ids) {
      this.ids = JSON.parse(ids);
      this.setRequest(this.ids[this.ids.length - 1]);
    }
    // 保存播放条的头部
    this.head = this.$refs.head;
  },
};
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  align-items: center;
  height: 7rem;
  padding: 1rem;
  background: #f6f6f8;
  .song-info {
    display: flex;
    .img {
      position: relative;
      width: 5rem;
      height: 5rem;
      cursor: pointer;
      margin-right: 1rem;
      img {
        width: 100%;
        height: 100%;
      }
      &:hover {
        .modal {
          display: block;
        }
      }
      .modal {
        display: none;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        text-align: center;
        line-height: 5rem;
        color: #fff;
        background: rgba(0, 0, 0, 0.3);
        pointer-events: none;
      }
    }
    .song {
      p {
        width: 18rem;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        margin-bottom: 0;
      }
      .song-name {
        font-size: 1.8rem;
      }
    }
    .ico {
      display: inline-block;
      height: 2.3rem;
      width: 2.3rem;
      cursor: pointer;
      background-image: url(/img/player.262d587f.png);
      background-position: 0 -96px;
      color: #eee;
    }
  }
  .controls {
    width: 49rem;
    .top {
      display: flex;
      align-items: center;
      justify-content: center;
      .cm {
        cursor: pointer;
        &:hover {
          color: #000;
        }
      }
      .mode {
        font-size: 1.9rem;
        margin-right: 2rem;
      }
      .prev,
      .next {
        font-size: 2.5rem;
      }
      .run {
        font-size: 3rem;
        margin: 0 2rem;
      }
    }
    .play {
      display: flex;
      align-items: center;
      justify-content: center;
      .prograss {
        position: relative;
        width: 36rem;
        height: 0.6rem;
        background: #c1c1c2;
        margin: 0 0.6rem;
        cursor: pointer;
        .move {
          height: 100%;
          background: #f40;
        }
        // &:hover {
        //   height: 0.6rem;
        //   .head {
        //     display: block;
        //   }
        // }
        .head {
          // display: none;
          display: block;
          position: absolute;
          left: -0.5rem;
          top: -0.2rem;
          height: 1rem;
          width: 1rem;
          background: #f40;
          border-radius: 50%;
        }
      }
      .start,
      .end {
        color: #ccc;
      }
    }
  }
  .others {
    display: flex;
    width: 22rem;
    // justify-content: space-between;
    align-items: center;
    .cm {
      margin: 0 0.6rem;
      cursor: pointer;
    }
    .quality {
      padding: 0.3rem;
      border: 1px solid #222;
      font-size: 1.2rem;
      text-align: center;
    }
    .volume {
      font-size: 2.3rem;
    }
    .volume-prograss {
      width: 8rem;
      height: 0.4rem;
      background: #ccc;
      .v-p {
        height: 100%;
        width: 3rem;
        background: #f40;
      }
    }
    .menu-unfold {
      margin-left: 1rem;
      font-size: 2rem;
    }
  }
}
</style>